package me.boot.web.common.interceptor;

import lombok.extern.slf4j.Slf4j;
import me.boot.common.context.ContextUtil;
import me.boot.common.data.model.AppMode;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * 拦截器：
 * 将请求头数据，封装到 ContextHandler(ThreadLocal)
 * <p>
 * 该拦截器要优先于系统中其他的业务拦截器
 * <p>
 */
@Slf4j
public class HeaderThreadLocalInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        AppMode appMode = ContextUtil.getAppMode();
        if (appMode == null) return true;

        // mono
        if (appMode.equals(AppMode.Mono)) {
//            ContextUtil.setUserId(WebUtils.getHeader(request, ContextConst.JWT_KEY_USER_ID));
//            ContextUtil.setAccount(getHeader(request, ContextConstants.JWT_KEY_ACCOUNT));
//            ContextUtil.setName(getHeader(request, ContextConstants.JWT_KEY_NAME));
//            ContextUtil.setTenant(getHeader(request, ContextConstants.JWT_KEY_TENANT));
//            ContextUtil.setSubTenant(getHeader(request, ContextConstants.JWT_KEY_SUB_TENANT));
//
//            String traceId = request.getHeader(ContextConstants.TRACE_ID_HEADER);
//            MDC.put(ContextConstants.LOG_TRACE_ID, StrUtil.isEmpty(traceId) ? StrUtil.EMPTY : traceId);
//            MDC.put(ContextConstants.JWT_KEY_TENANT, getHeader(request, ContextConstants.JWT_KEY_TENANT));
//            MDC.put(ContextConstants.JWT_KEY_SUB_TENANT, getHeader(request, ContextConstants.JWT_KEY_SUB_TENANT));
//            MDC.put(ContextConstants.JWT_KEY_USER_ID, getHeader(request, ContextConstants.JWT_KEY_USER_ID));
        }

        // cloud

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        ContextUtil.clear();
    }
}
